package com.jinghao.extend.interceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jinghao.core.common.util.JhLoggerUtil;
import com.jinghao.sys.service.ISysAccountService;

/** 
  * @Description:
  * @author  sxl 
  * @date 创建时间：2017年12月1日 下午8:50:32 
  * @version 1.0 
*/
public class RequestInterceptor extends HandlerInterceptorAdapter{
	
	private boolean enabled = true; 
	
	public String returnType;
	
	public String returnUrl;
	
	public static String returnType_1="Redirect";
	
	public static String returnType_2="Json";
	
	public boolean isEnabled() {
		return enabled;
	}
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}
	public String getReturnType() {
		return returnType;
	}
	public void setReturnType(String returnType) {
		this.returnType = returnType;
	}
	public String getReturnUrl() {
		return returnUrl;
	}
	public void setReturnUrl(String returnUrl) {
		this.returnUrl = returnUrl;
	}
	@Resource
	private ISysAccountService sysAccountService;
	private final Logger log = JhLoggerUtil.getLogger();
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {  
    	
    	//首先判断是否是Debug模式(全局)，如果否则使拦截器失效  
        if(!this.enabled){ return true;  }
    	
    	log.info("==============执行顺序: RequestInterceptor、================");  
    	String accessToken=request.getHeader("accessToken");
    	log.info("accessToken:"+accessToken);  
		if(accessToken==null||!sysAccountService.updateCheckIsLogin(accessToken)||accessToken.trim().equals("")){
			if(returnType==null||returnType.trim().equals("")){
				//不存在参数
			}else if(returnType.equals(RequestInterceptor.returnType_2)){
				 PrintWriter out = response.getWriter();  
	             out.print("{\"code\":\"-1\",\"success\":\"\",\"messages\":\"账户未进行登录或已超时，请重新登录！\",\"data\":\"\"}"); 
			}else if(returnType.equals(RequestInterceptor.returnType_1)){//跳转
				 log.info("Interceptor：跳转到login页面！");  
		         request.getRequestDispatcher(returnUrl).forward(request, response);  
			}
			return false;
		}
    	return true;
    }
}

 
